package im.yisme.view.activities;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import im.yisme.R;
import im.yisme.controler.service.CtrlServiceProvider;
import im.yisme.controler.service.LyricsCtrlService;
import im.yisme.model.Lyrics;
import im.yisme.model.service.LyricsRepositoryService;
import im.yisme.model.service.ModelServiceProvider;
import im.yisme.view.service.ViewService;
import im.yisme.view.service.ViewServiceProvider;
import im.yisme.view.ui.MainView;
import im.yisme.view.ui.animation.BGP;
import im.yisme.view.ui.animation.LyricsLibAnimationSet;
import im.yisme.view.ui.util.LyricsLibAdapter;
import im.yisme.vo.LyricsVO;
import im.yisme.vo.MusicVO;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class LyricsLibraryActivity extends Rotate3DActivity {
	private ViewService viewCtrl;
	private LyricsCtrlService ctrl;
	private LyricsRepositoryService model;
	private InputMethodManager imm;
	
	//-------------------------------
	//音乐库界面组件
	private ViewGroup lyricsLib;
	private ListView list;
	private int selectedItem;
	private ViewGroup detailPane;
	private TextView artistText,noteNumText,scoreText;
	private ImageButton modifyButton,uploadButton,backButton;
	private ImageView title,uploaded;
	//修改界面组件
	private ViewGroup modifyPane;
	private EditText musicNameEdit,artistEdit;
	private ImageButton sureButton,cancelButton;
	//
	private MainView mainView;
	//-------------------------------
	
	//-------------------------------
	//动画
	private LyricsLibAnimationSet animationSet;
	private Handler bgpHandler;
	private BGP bgp; 
	//-------------------------------
	
	//-------------------------------
	//歌谱文件数据
	private ArrayList<LyricsVO> lyricsVOList1,lyricsVOList2;
	//-------------------------------
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lyricslib);

		viewCtrl=ViewServiceProvider.getViewService();
		ctrl = CtrlServiceProvider.getLyricsCtrlService();
		model = ModelServiceProvider.getLyricsRepositoryService();
		model.loadFile();
		init();
		
	}
	
	private void jumpToMain(){
		Intent intent = new Intent(this,MainActivity.class);
		viewCtrl.jumpTo(intent);
	}
	
	protected void onResume(){
		super.onResume();
		viewCtrl.updateTopActivity(this);
	}
	protected void onRestart(){
		super.onRestart();
		bgp = new BGP(bgpHandler);
		bgp.start();
	}
	
	protected void onStop(){
		super.onStop();
		bgp.stopRunning();
		if(mainView != null) mainView.stop();
		finish();
	}
	
	private void init(){
		
		lyricsLib = (RelativeLayout) findViewById(R.id.lyricslib);
		imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		
		
		initButtons();
		initTitle();
		initDetailPane();
		initList();
		initAnimation();
		
		
	}
	private void initAnimation() {
		// TODO Auto-generated method stub
		animationSet = new LyricsLibAnimationSet(this, this, list, detailPane, backButton, title);
		
		bgpHandler = new Handler(){
			public void handleMessage(Message m){
				switch (m.what) {
				case 0:
					lyricsLib.setBackgroundResource(R.drawable.bgp1);
					break;
				case 1:
					lyricsLib.setBackgroundResource(R.drawable.bgp2);
					break;
				case 2:
					lyricsLib.setBackgroundResource(R.drawable.bgp3);
					break;
				case 3:
					lyricsLib.setBackgroundResource(R.drawable.bgp4);
					break;
				default:
					break;
				}
				
			}
		};
		bgp = new BGP(bgpHandler);
		bgp.start();
	}

	private void initList(){
		list = (ListView) findViewById(R.id.listView_lyricsLib);
		
		Iterator<LyricsVO> it = model.getLyricsList();
		
		ArrayList<Map<String, Object>> data1=new ArrayList<Map<String,Object>>();
        ArrayList<Map<String, Object>> data2=new ArrayList<Map<String,Object>>();
		lyricsVOList1 = new ArrayList<LyricsVO>();
		lyricsVOList2 = new ArrayList<LyricsVO>();
        
        
        while (it.hasNext()) {
			LyricsVO lyricsVO = it.next();
			Map<String,Object> item = new HashMap<String,Object>(); 
			item.put("lyricsName", lyricsVO.getName());
			
			switch (lyricsVO.getSource()) {
			case Lyrics.OFFICIAL:
				item.put("official", true);
				data2.add(item);
				lyricsVOList2.add(lyricsVO);
				break;
			case Lyrics.ORIGINAL:
				data1.add(item);
				lyricsVOList1.add(lyricsVO);
				break;
			case Lyrics.UNORIGINAL:
				item.put("official", false);
				data2.add(item);
				lyricsVOList2.add(lyricsVO);	
				break;
			default:
				break;
			}
		}
        
		
		
		LyricsLibAdapter adapter = new LyricsLibAdapter(this, this, data1, data2);
		
		list.setAdapter(adapter);
		
		selectedItem = 1;
		updateDetailPaneInfo();
		
		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {
				// TODO Auto-generated method stub				
							
				if(arg2 == 0 || lyricsVOList1.size()+1 == arg2) return;
				if(arg2 != selectedItem){
				    detailPane.startAnimation(animationSet.detailPaneZoomOut);
				    
				    selectedItem = arg2;
				}
			}
		});
	}
	public void deleteLyrics(int position, int which){
		if(which == 1)
			ctrl.removeLyricsFromRepository(lyricsVOList1.get(position));
		else 
			ctrl.removeLyricsFromRepository(lyricsVOList2.get(position));
		initList();
	}
	
	private void initButtons(){
		
		modifyButton = (ImageButton) findViewById(R.id.imageButton_modify);
		uploadButton = (ImageButton) findViewById(R.id.imageButton_upload);
		backButton = (ImageButton) findViewById(R.id.imageButton_back);
		
		modifyButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				detailPane.startAnimation(animationSet.detailPaneRightOut);
				list.startAnimation(animationSet.listLeftOut);
				backButton.startAnimation(animationSet.backButtonBottomOut);
				title.startAnimation(animationSet.titleFadeOut);
				
				LyricsVO lyricsVO = getSelectedLyricsVO();
				initModify(lyricsVO.getName(),artistText.getText());
				modifyPane.startAnimation(animationSet.modifyPaneTopIn);
			}
		});
		
		uploadButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		backButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				lyricsLib.startAnimation(rOutAnimation);
				mainView = new MainView(LyricsLibraryActivity.this);
				setContentView(mainView);
				mainView.startAnimation(lInAnimation);		
				lInAnimation.setAnimationListener(new AnimationListener() {
					
					public void onAnimationStart(Animation animation) {}	
					public void onAnimationRepeat(Animation animation) {}
					
					public void onAnimationEnd(Animation animation) {
						// TODO Auto-generated method stub
						back();
					}
				});
			}
		});
	}
	private void initDetailPane(){
		detailPane = (RelativeLayout) findViewById(R.id.relativeLayout_detailPane);
		artistText = (TextView) findViewById(R.id.textView_artist);
		noteNumText = (TextView) findViewById(R.id.textView_noteNum);
		scoreText = (TextView) findViewById(R.id.textView_score);
		uploaded = (ImageView) findViewById(R.id.imageView_uploaded);
	}
	private void initTitle(){
		title = (ImageView) findViewById(R.id.imageView_title);
	}
	private void initModify(String musicName,CharSequence charSequence){
	
		modifyPane = (ViewGroup) findViewById(R.id.relativeLayout_modify);
		musicNameEdit = (EditText) findViewById(R.id.editText_musicName);
		musicNameEdit.setText(musicName);
		artistEdit = (EditText) findViewById(R.id.editText_artist);
		artistEdit.setText(charSequence);
		sureButton = (ImageButton) findViewById(R.id.imageButton_sure);
		sureButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				modifyPackUp();
				LyricsVO lyricsVO = getSelectedLyricsVO();
				lyricsVO.setName(musicNameEdit.getText().toString());
				lyricsVO.setArtist(artistEdit.getText().toString());
				ctrl.alterLyricsInfo(lyricsVO);
				initList();
			}
		});
		cancelButton = (ImageButton) findViewById(R.id.imageButton_cancel);
		cancelButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				modifyPackUp();
			
			}
		});
		animationSet.registerModifyPane(modifyPane);
		
	}
	private void modifyPackUp(){
		modifyPane.startAnimation(animationSet.modifyPaneTopOut);
		
		detailPane.startAnimation(animationSet.detailPaneRightIn);
		list.startAnimation(animationSet.listLeftIn);
		backButton.startAnimation(animationSet.backButtonBottomIn);
		title.startAnimation(animationSet.titleFadeIn);
	}
	private void back(){
		jumpToMain();
		overridePendingTransition(0, 0);
	}
	
	public void onBackPressed(){}
	public boolean onTouchEvent(MotionEvent event) {  
        // TODO Auto-generated method stub  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            if (this.getCurrentFocus() != null) {  
                if (this.getCurrentFocus().getWindowToken() != null) {  
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),  
                            InputMethodManager.HIDE_NOT_ALWAYS);  
                }  
            }  
        }  
        return super.onTouchEvent(event);  
    }
	public void updateDetailPaneInfo(){
		if(lyricsVOList1.size() == 0 && lyricsVOList2.size() == 0) return;	
		
		LyricsVO lyricsVO = getSelectedLyricsVO();
		
		
		artistText.setText(lyricsVO.getArtist());
		noteNumText.setText(lyricsVO.getNoteNum()+"");
		
		switch (lyricsVO.getSource()) {
		case Lyrics.OFFICIAL:
			//downloadTimesText.setText();
			scoreText.setText(lyricsVO.getScore()+"");
			uploadButton.setVisibility(View.INVISIBLE);
			modifyButton.setVisibility(View.INVISIBLE);
			uploaded.setVisibility(View.INVISIBLE);
			break;
		case Lyrics.ORIGINAL:
			if(lyricsVO.isUploaded()){
				//downloadTimesText.setText();
				scoreText.setText(lyricsVO.getScore()+"");
				uploadButton.setVisibility(View.INVISIBLE);
				modifyButton.setVisibility(View.VISIBLE);
				uploaded.setVisibility(View.VISIBLE);
			}
			else {
				scoreText.setText("未上传");
				uploadButton.setVisibility(View.VISIBLE);
				modifyButton.setVisibility(View.VISIBLE);
				uploaded.setVisibility(View.INVISIBLE);
			}
			break;
		case Lyrics.UNORIGINAL:
			scoreText.setText(lyricsVO.getScore()+"");
			uploadButton.setVisibility(View.INVISIBLE);
			modifyButton.setVisibility(View.VISIBLE);
			uploaded.setVisibility(View.INVISIBLE);
			
			break;
		default:
			break;
		}
	}
	
	private LyricsVO getSelectedLyricsVO(){
		if(lyricsVOList1.size() == 0 && lyricsVOList2.size() == 0) return null;	
		
		if(selectedItem > lyricsVOList1.size()){
			return lyricsVOList2.get(selectedItem-lyricsVOList1.size()-2);
		}
		else {
			return lyricsVOList1.get(selectedItem-1);
		}
	}
}
